<template>
  <div class="user_wrap">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主题内容 -->
    <el-card class="box-card">
      <!-- 搜索框 -->
      <el-row :gutter="20" style="margin-bottom: 15px">
        <el-col :span="6">
          <el-input
            v-model.trim="search.query"
            placeholder="请输入内容"
            clearable
            maxlength="10"
            @clear="handleClear"
            @keyup.enter.native="handleSearch"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handleSearch"
            />
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button
            type="primary"
            style="margin-left: 15px"
            @click="dialogVisible = true"
          >添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表 -->
      <el-table
        ref="tableRef"
        :data="usersData"
        border
        max-height="600"
      >
        <el-table-column label="序号" type="index" width="50" align="center">
          <template slot-scope="scope">
            <span>{{
              (search.pagenum - 1) * search.pagesize + scope.$index + 1
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="180" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="mobile" label="电话" width="180" />
        <el-table-column prop="role_name" label="角色" width="180" />
        <el-table-column prop="mg_state" label="状态" width="180">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="switchChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="250" align="center">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" @click="editUser(scope.row.id)" />
            <!-- 分配权限按钮-->
            <el-tooltip
              effect="dark"
              content="角色分配"
              placement="top"
              :enterable="false"
            >
              <el-button type="warning" icon="el-icon-s-tools" @click="setRoles(scope.row)" />
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" @click="delectUser(scope.row.id)" />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        :current-page="search.pagenum"
        :page-sizes="[5, 15, 20, 25]"
        :page-size="search.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <!-- 添加用户弹出框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="dialogVisible"
        width="50%"
        @close="cancle()"
      >
        <!-- 主体区 -->
        <el-form
          ref="addFormRef"
          :model="addForm"
          label-width="70px"
          :rules="addFormRules"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email" />
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancle">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户信息弹出框 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="editUserVisible"
        width="50%"
        @close="editUserCancle()"
      >
        <!-- 主体内容 -->
        <el-form
          ref="editFormRef"
          :model="editForm"
          label-width="70px"
          :rules="editFormRules"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" :disabled="true" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" />
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editUserCancle">取 消</el-button>
          <el-button type="primary" @click="editUserComfirm">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="rolesVisible"
        width="50%"
        @close="rolesCancle()"
      >
        <!-- 主体内容 -->
        <el-form
          :model="rolesInfo"
          label-width="100px"
        >
          <el-form-item label="当前用户名:">
            <el-input v-model="rolesInfo.username" :disabled="true" style="width:300px;" />
          </el-form-item>
          <el-form-item label="当前角色名:">
            <el-input v-model="rolesInfo.role_name" :disabled="true" style="width:300px;" />
          </el-form-item>
          <el-form-item label="分配新角色:">
            <el-select v-model="roleser" placeholder="请选择角色" style="width:300px;">
              <el-option
                v-for="item in rolesInfo.rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="rolesCancle">取 消</el-button>
          <el-button type="primary" @click="rolesComfirm">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import { users,
  upUsers,
  checkUser,
  editCheckUser,
  delectUserRadio,
  rolesList,
  showUsersRole
} from '@/api/login';
import { addUsers } from '@/api/login';
export default {
  name: 'User',
  components: {},
  data() {
    /* 自定义邮箱的校验规则 */
    var checkEmail = (rule, value, callback) => {
      /* 校验邮箱的正则 */
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
      if (reg.test(value)) {
        // 合法的邮箱
        return callback();
      }
      // 不合法的邮箱
      callback(new Error('请输入邮箱'));
    };
    /* 自定义电话号的校验规则 */
    var checkMobile = (rule, value, callback) => {
      /* 校验邮箱的正则 */
      const reg =
        /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
      if (reg.test(value)) {
        // 合法的电话
        return callback();
      }
      // 不合法的电话
      callback(new Error('请输入手机号'));
    };
    return {
      roleser: '', // 选中的角色
      /* 分配角色对话框是否可见 */
      rolesVisible: false,
      /* 修改表单验证规则 */
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      /* 修改表单的数据*/
      editForm: {},
      /* 添加表单验证规则 */
      addFormRules: {
        username: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 8, message: '长度在 5 到 8 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      /* 添加用户表单 */
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      /* 控制修改用户对话框的显示与隐藏 */
      editUserVisible: false,
      /* 控制添加用户对话框的显示与隐藏 */
      dialogVisible: false,
      search: {
        query: '', // 查询条件
        pagenum: 1, // 当前页
        pagesize: 5 // 每页条数
      },
      total: 0, // 总条数
      usersData: [], // 表格数据
      rolesInfo: {}// 将被分配权限的用户信息
    };
  },
  mounted() {
    this.getUser();
  },
  methods: {
    // 取消分配角色
    rolesCancle() {
      this.rolesInfo = {};
      this.roleser = '';
      this.rolesVisible = false;
    },
    // 确定分配角色
    rolesComfirm() {
      showUsersRole(this.rolesInfo.id, { rid: this.roleser }).then((res) => {
        if (!this.roleser) return this.$message.error('请选择角色!');
        const { msg, status } = res.data.meta;
        if (status !== 200) return this.$message.error(msg);
        this.getUser();
        this.$message.success(msg);
        this.rolesVisible = false;
      });
    },
    /* 设置分配角色 */
    setRoles(row) {
      this.rolesInfo = row;
      rolesList().then((res) => {
        const { msg, status } = res.data.meta;
        if (status !== 200) return this.$message.error(msg);
        // 角色下拉框数据
        this.rolesInfo.rolesList = res.data.data;
        this.rolesVisible = true;
      });
    },
    /* 删除单个用户 */
    delectUser(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delectUserRadio(id).then((res) => {
          const { msg, status } = res.data.meta;
          if (status !== 200) return this.$message.error(msg);
          this.getUser();
          this.$message.success('删除成功！');
        }).catch((err) => {
          console.log(err);
        });
      }).catch(() => {
        this.$message.info('取消删除！');
      });
    },
    /* 修改用户信息 */
    editUser(id) {
      checkUser(id).then((res) => {
        const { data, meta } = res.data;
        if (meta.status !== 200) return this.$message.error(meta.msg);
        this.editForm = data;
        this.editUserVisible = true;
      }).catch((err) => {
        console.log(err);
      });
    },
    /* 修改用户 确定*/
    editUserComfirm() {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return false;
        /* 添加用户的网络请求 */
        const { id, email, mobile } = this.editForm;
        const params = {
          id, email, mobile
        };
        editCheckUser(params).then((res) => {
          const msg = res.data.meta.msg;
          if (res.data.meta.status !== 200) return this.$message.error(msg);
          this.$message.success(msg);
          this.getUser();
          this.dialogVisible = false;
        }).catch((error) => {
          console.log(error);
        });
      });
      this.editUserVisible = false;
    },
    /*  修改用户 取消 (关闭)*/
    editUserCancle() {
      this.editUserVisible = false;
      // 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      this.$refs.editFormRef.resetFields();
    },
    /* 添加用户 取消 (关闭)*/
    cancle() {
      this.dialogVisible = false;
      // 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      this.$refs.addFormRef.resetFields();
    },
    /* 添加用户 确定 */
    confirm() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return false;
        /* 添加用户的网络请求 */
        addUsers(this.addForm).then((res) => {
          const msg = res.data.meta.msg;
          if (res.data.meta.status !== 201) return this.$message.error(msg);
          this.$message.success(msg);
          this.getUser();
          this.dialogVisible = false;
        });
      });
    },
    /* 监听清空输入框 */
    handleClear() {
      this.getUser();
    },
    /* 搜索查询 */
    handleSearch() {
      this.getUser();
    },
    /* 监听状态改变 */
    switchChange(userInfo) {
      const { id, mg_state } = userInfo;
      upUsers(id, mg_state).then((res) => {
        if (res.data.meta.status !== 200) {
          /* 如果更新失败,要将状态还原 */
          userInfo.mg_state = !userInfo.mg_state;
          return this.$message.error(res.data.meta.msg);
        }
        this.$message.success(res.data.meta.msg);
      });
    },
    /* 获取用户列表数据 */
    getUser() {
      users(this.search).then((res) => {
        if (res.data.meta.status !== 200) {
          return this.$message.error(res.data.meta.msg);
        }
        const { pagenum, users, total } = res.data.data;
        this.pagenum = pagenum;
        this.usersData = users;
        this.total = total;
      });
    },
    /* 监听pageSize的改变 */
    handleSizeChange(newSize) {
      this.search.pagesize = newSize;
      this.getUser();
    },
    /* 监听CurrentPage的改变 */
    handleCurrentChange(newPage) {
      this.search.pagenum = newPage;
      this.getUser();
    }
  }
};
</script>
<style scoped lang='scss'>
.box-card {
  width: 100%;
  margin-top: 15px;
}
</style>
